import React, {useEffect, useRef, useState} from 'react';
import {List, message, Modal, Button, Spin, Form, FormInstance} from 'antd';
import {PlusOutlined} from '@ant-design/icons';
import {
  ModalForm,
  ProForm,
  ProFormCheckbox,
  ProFormDatePicker, ProFormDateRangePicker,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  StepsForm,
} from "@ant-design/pro-form";
import {useModel} from "@@/plugin-model/useModel";
import styles from "@/components/RightContent/index.less";
import {doCaptcha} from "@/services/ant-design-pro/api";
import {changePassword, changePhone, checkPhone} from "@/pages/Account/Settings/service";

type Unpacked<T> = T extends (infer U)[] ? U : T;

const passwordStrength = {
  strong: <span className="strong">强</span>,
  medium: <span className="medium">中</span>,
  weak: <span className="weak">弱 Weak</span>,
};
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};
const SecurityView: React.FC = () => {
  const {initialState, setInitialState} = useModel('@@initialState');

  const [visible, setVisible] = useState(false);
  const [changePwdVisible, setChangePwdVisible] = useState(false);
  const changePwdForm = useRef<FormInstance>();
  const changePhoneForm = useRef<FormInstance>();
  const checkPhoneForm = useRef<FormInstance>();

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const {currentUser} = initialState;

  if (!currentUser || !currentUser.name) {
    return loading;
  }


  const getData = () => [
    {
      title: '账户密码',
      description: (
        <>
          建议密码长度8位以上，大小写字母、数字和其他符号相组合
          {/*当前密码强度：*/}
          {/*{passwordStrength.strong}*/}
        </>
      ),
      actions: [<a key="Modify" onClick={() => setChangePwdVisible(true)}>修改密码</a>],
    },
    {
      title: '绑定手机',
      description: `已绑定手机：${currentUser.phone}`,
      actions: [<a key="Modify" onClick={() => setVisible(true)}>更换手机号</a>],
    },
    // {
    //   title: '密保问题',
    //   description: '未设置密保问题，密保问题可有效保护账户安全',
    //   actions: [<a key="Set">设置</a>],
    // },
    // {
    //   title: '备用邮箱',
    //   description: `已绑定邮箱：ant***sign.com`,
    //   actions: [<a key="Modify">修改</a>],
    // },
    // {
    //   title: 'MFA 设备',
    //   description: '未绑定 MFA 设备，绑定后，可以进行二次确认',
    //   actions: [<a key="bind">绑定</a>],
    // },
  ];

  const data = getData();

  const [count, setCount]: [number, any] = useState(0);
  const [count1, setCount1]: [number, any] = useState(0);
  let interval: number | undefined;
  let interval1: number | undefined;

  useEffect(
    () => () => {
      clearInterval(interval);
    },
    [interval],
  );

  const onGetCaptcha = async (username: any, callback: (code) => {}) => {

    // const username = p ?? currentUser.account;
    if (!username) {
      message.error('请输入注册手机号');
    } else {
      try {
        const msg = await doCaptcha(username);
        console.log(msg);
        if (msg.status === 'ok') {
          let counts = 59;
          if (msg.data) {
            callback(msg.data);
            // changePwdForm.current?.setFieldsValue({code: msg.data});
          }
          setCount(counts);
          interval = window.setInterval(() => {
            counts -= 1;
            setCount(counts);
            if (counts === 0) {
              clearInterval(interval);
            }
          }, 1000);
        } else {
          message.error("发送失败");
        }
      } catch (error) {
      }
    }
  };
  const onGetCaptcha1 = async (username: any, callback: (code) => {}) => {

    // const username = p ?? currentUser.account;
    if (!username) {
      message.error('请输入注册手机号');
    } else {
      try {
        const msg = await doCaptcha(username);
        console.log(msg);
        if (msg.status === 'ok') {
          let counts = 59;
          if (msg.data) {
            callback(msg.data);
            // changePwdForm.current?.setFieldsValue({code: msg.data});
          }
          setCount1(counts);
          interval1 = window.setInterval(() => {
            counts -= 1;
            setCount1(counts);
            if (counts === 0) {
              clearInterval(interval1);
            }
          }, 1000);
        } else {
          message.error("发送失败");
        }
      } catch (error) {
      }
    }
  };


  return (
    <>
      <List<Unpacked<typeof data>>
        itemLayout="horizontal"
        dataSource={data}
        renderItem={(item) => (
          <List.Item actions={item.actions}>
            <List.Item.Meta title={item.title} description={item.description}/>
          </List.Item>
        )}
      />

      <ModalForm
        // @ts-ignore
        visible={changePwdVisible}
        title={"修改密码"}
        formRef={changePwdForm}
        width={500}
        labelCol={{span: 6}}
        wrapperCol={{span: 14}}
        //   labelCol={ span: 4 }
        // wrapperCol= { span: 14 }
        modalProps={{destroyOnClose: true, maskClosable: false}}
        onVisibleChange={setChangePwdVisible}
        layout={"horizontal"}
        // labelWidth="200px"
        // trigger={
        //   <Button type="primary">
        //     <PlusOutlined/>
        //     新建表单
        //   </Button>
        // }
        onFinish={async (values: any) => {
          // await waitTime(2000);

          let newVar = await changePassword(values);
          console.log(values, newVar);
          if (newVar.code == 200) {
            message.success('密码修改成功');
            setChangePwdVisible(false)
          } else {
            message.error(newVar.msg);
          }
        }}
        initialValues={{
          username: currentUser.account,
          phone: currentUser.phone,
          code: undefined,
          password: undefined,
        }}
      >
        <ProFormText name="username" hidden/>
        <ProFormText name="phone" label="手机号码" readonly={true}/>
        <ProFormText
          name="code"
          label="验证码"
          required={true}
          addonAfter={
            <Button
              disabled={!!count}
              style={{display: 'block', width: '100%'}}
              onClick={() => {
                let u = changePwdForm.current?.getFieldValue("username");
                onGetCaptcha(u, (code) => {
                  changePwdForm.current?.setFieldsValue({code: code});
                }).then(r => {
                  console.log(r)
                })
              }}
            >
              {count ? `${count} s` : '获取验证码'}
            </Button>}
        />
        <ProFormText.Password
          name="password"
          label="新密码"
          required={true}
        />
      </ModalForm>

      <StepsForm
        onFinish={async (values) => {
          console.log(values);
          // await waitTime(1000);
          // setVisible(false);
          // message.success('提交成功');

          let newVar = await changePhone(values);
          console.log(values, newVar);
          if (newVar.code == 200) {
            message.success('手机号修改成功');
            setVisible(false);
          } else {
            message.error(newVar.msg);
          }
        }}
        // current={1}
        submitter={{
          render: (props, dom) => {
            if (props.step === 0) {
              return (
                <div style={{textAlign: 'center', width: "100%"}}>
                  <Button type="primary" onClick={() => props.onSubmit?.()} shape={"round"}>
                    验证手机号
                  </Button>
                </div>
              );
            }

            if (props.step === 1) {
              return [
                // <Button key="pre" onClick={() => props.onPre?.()} shape={"round"} size={"large"}>
                //   返回修改信息
                // </Button>,
                <div style={{textAlign: 'center', width: "100%"}}>
                  <Button
                    type="primary"
                    key="goToTree"
                    onClick={() => props.onSubmit?.()} shape={"round"}>
                    修改手机号
                  </Button>
                </div>
              ];
            }

            return [];
          },
        }}
        formProps={{
          validateMessages: {
            required: '此项为必填项',
          },
        }}

        stepsFormRender={(dom, submitter) => {
          return (
            <Modal
              title="修改绑定手机号"
              width={600}
              onCancel={() => setVisible(false)}
              visible={visible}
              footer={submitter}
              destroyOnClose={true}
              maskClosable={false}
            >
              {dom}
            </Modal>
          );
        }}
      >
        <StepsForm.StepForm
          name="base"
          title="验证手机号"
          layout={"horizontal"}
          formRef={checkPhoneForm}
          onFinish={async (values: any) => {
            let newVar = await checkPhone(values);
            console.log(values, newVar);
            if (newVar.code == 200) {
              return true;
            } else {
              message.error(newVar.msg);
              return false;
            }
          }}
          initialValues={{
            username: currentUser.account,
            password: currentUser.phone,
            phone: currentUser.phone,
            code: undefined,
          }}
        >
          <ProFormText name="username" hidden/>
          <ProFormText name="password" hidden/>
          <ProFormText name="phone" label="手机号码" readonly={true}/>
          <ProFormText
            name="code"
            label="验证码"
            required={true}
            addonAfter={
              <Button
                disabled={!!count}
                style={{display: 'block', width: '100%'}}
                // onClick={() => {
                //   let u = checkPhoneForm.current?.getFieldValue("username");
                //   onGetCaptcha(u).then(r => {
                //   })
                // }}
                onClick={() => {
                  let u = checkPhoneForm.current?.getFieldValue("username");
                  onGetCaptcha(u, (code) => {
                    checkPhoneForm.current?.setFieldsValue({code: code});
                  }).then(r => {
                    console.log(r)
                  })
                }}
              >
                {count ? `${count} s` : '获取验证码'}
              </Button>}
          />
        </StepsForm.StepForm>
        <StepsForm.StepForm
          name="checkbox"
          title="新手机号"
          formRef={changePhoneForm}
          initialValues={{
            username: undefined,
            password: currentUser.phone,
            phone: currentUser.phone,
            code: undefined,
          }}>

          <ProFormText name="password" hidden/>
          <ProFormText name="username" label="新手机号码" required={true}/>
          <ProFormText
            name="code"
            label="验证码"
            required={true}
            addonAfter={
              <Button
                disabled={!!count1}
                style={{display: 'block', width: '100%'}}
                // onClick={() => {
                //   let u = changePhoneForm.current?.getFieldValue("username");
                //   onGetCaptcha(u).then(r => {
                //
                //   })
                // }}

                onClick={() => {
                  let u = changePhoneForm.current?.getFieldValue("username");
                  onGetCaptcha1(u, (code) => {
                    changePhoneForm.current?.setFieldsValue({code: code});
                  }).then(r => {
                    console.log(r)
                  })
                }}
              >
                {count1 ? `${count1} s` : '获取验证码'}
              </Button>}
          />
        </StepsForm.StepForm>
      </StepsForm>
    </>
  );
};

export default SecurityView;
